#ifndef reqhandler_h
#define reqhandler_h

#include <Arduino.h>
#include "variable.h"
#include "serial.h"
#include "logger.h"
#include "sensor.h"
#include "pins.h"
#include "pid.h"

// 处理串口请求
void loop_reqhandler()
{
    if (Serial.available() > 0)
    {
        // 解析命令行
        req = Serial.readStringUntil('\n');
        // logf("[CMD] %s ", req.c_str());
        int spaceIndex = req.indexOf(' ');
        name = req.substring(0, spaceIndex);
        String valueStr = req.substring(spaceIndex + 1);
        valueStr.trim();
        value = valueStr.toInt();
        // logf("[name] %s ", name.c_str());
        // logf("[value] %d ", value);
        int pin = getPinByName(name);

        // 各种mos开关
        if (pin != -1)
        {
            digitalWrite(pin, value);
        }
        // 电磁搅拌
        else if (name == "Motor")
        {
            bool ok = setMotorSpeed(value);
            // Serial.print("Modbus write result: ");
            // Serial.println(ok ? "Success" : "Fail");
        }
        // 风扇PWM调速
        else if (name == "Fan1")
        {
            analogWrite(Fan1, value);
        }
        // 泄气阀阀门开度
        else if (name == "Valve2")
        {
            valve2_open(value); // 0-4095对应0-5v对应阀门开度0-100%
        }
        // 泄气阀自动调节开度
        else if (name == "Valve2_Release")
        {
            xTaskCreate(valve2_release_task, "valve2_release", 1024, NULL, 1, NULL); // 泄气阀逐渐打开
        }
        // 温度传感器
        else if (name == "getTempDuct")
        {
            adc = analogRead(TempDuct);
            float tempDuctValue = adcToTemp2(adc);
            logf("TempDuct %f", tempDuctValue);
        }
        else if (name == "getTempPump")
        {
            adc = analogRead(TempPump);
            float tempPumpValue = adcToTemp2(adc);
            logf("TempPump %f", tempPumpValue);
        }
        else if (name == "getReactorTemp_out")
        {
            adc = analogRead(TempReactor);
            float tempReactorValue = adcToTemp2(adc);
            logf("ReactorTemp_out %f", tempReactorValue);
        }
        else if (name == "getReactorTemp")
        {
            float tempReactorValue = adcToTemp(1);
            logf("ReactorTemp %f", tempReactorValue);
        }
        // 压力传感器
        else if (name == "getPumpPres")
        {
            float presPumpValue = adcToPres();
            logf("PumpPres %f", presPumpValue);
        }
        // 设置温度目标值并进行PID控制
        else if (name == "setTempDuct")
        {
            targetDuctTemp = value;
            // 检查任务是否已存在
            if (ductTempTaskHandle == NULL)
            {
                xTaskCreate(duct_temp_control_task, "duct_temp", 1024, NULL, 1, &ductTempTaskHandle);
            }
        }
        else if (name == "setTempPump")
        {
            targetPumpTemp = value;
            // 检查任务是否已存在
            if (pumpTempTaskHandle == NULL)
            {
                xTaskCreate(pump_temp_control_task, "pump_temp", 1024, NULL, 1, &pumpTempTaskHandle);
            }
        }
        else if (name == "setReactorTemp")
        {
            targetReactorTemp = value;
            // 检查任务是否已存在
            if (reactorTempTaskHandle == NULL)
            {
                xTaskCreate(reactor_temp_control_task, "reactor_temp", 1024, NULL, 1, &reactorTempTaskHandle);
            }
        }

        // CO2泵相关功能
        // else
        // {
        //     bool found = false;
        //     for (int i = 0; i < cmdCount; ++i)
        //     {
        //         if (name.equals(cmdTable[i].name)) // 修改为 equals
        //         {
        //             found = true;
        //             if (cmdTable[i].needArg && cmdTable[i].funcWithArg)
        //             {
        //                 bool ok = cmdTable[i].funcWithArg(value);
        //                 // Serial.println(ok ? "Success" : "Fail");
        //             }
        //             else if (!cmdTable[i].needArg && cmdTable[i].funcNoArg)
        //             {
        //                 cmdTable[i].funcNoArg();
        //             }
        //             break;
        //         }
        //     }
        //     if (!found)
        //     {
        //         logln("Command not found"); // 更准确的提示
        //     }
        // }
        else if (name == "setMaxPres")
        {
            bool ok = setMaxPres(value);
        }
        else if (name == "setMinPres")
        {
            bool ok = setMinPres(value);
        }
        else if (name == "clearPres")
        {
            bool ok = clearPres();
        }
        else if (name == "getMaxPres")
        {
            getMaxPres();
        }
        else if (name == "getMinPres")
        {
            getMinPres();
        }
        else if (name == "setTraffic")
        {
            bool ok = setTraffic(value);
        }
        else if (name == "getTraffic")
        {
            getTraffic();
        }
        else if (name == "startPump")
        {
            bool ok = startPump();
        }
        else if (name == "stopPump")
        {
            bool ok = stopPump();
        }
        else if (name == "getPumpState")
        {
            getPumpState();
        }
        else if (name == "getPres")
        {
            getPres();
        }
        else if (name == "startPresSample")
        {
            bool ok = startPresSample(value);
        }
        else
        {
            Serial.println("Pin not found");
        }
    }
}

#endif
